/*
 * AisleNav Android Application
 * NavigateStoreActivity.java
 * project.AisleNav.NavigateActivity
 * 
 * CS495
 * 
 * Team:
 * 		Kirby Green
 * 		Mark Hale
 * 		Adam Warnock
 * 
 * Time: 6:14:34 PM
 * Date: Dec 4, 2011
 * 
 */
package project.AisleNav.NavigateActivity;

import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;

import project.AisleNav.R;
import project.AisleNav.Backend.Accelerometer;
import project.AisleNav.Backend.Grid;
import android.app.Activity;
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Matrix;
import android.graphics.Paint;
import android.graphics.Rect;
import android.graphics.RectF;
import android.os.Bundle;
import android.util.AttributeSet;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.Spinner;
import android.widget.Toast;

/**
 * NavigateStoreActivity.java Activity to navigate the store
 * 
 * @author Kirby Green
 * @version 0.1
 */
public class NavigateStoreActivity extends Activity {
	MySurfaceView mySurfaceView;
//	private static final String[] dotColor = { "White", "Red", "Green", "Blue" };
//	private ArrayAdapter<String> adapter;
	private static Grid myGrid;
	private static Accelerometer myAccel;
	
	static long running_time = 0L;

	/** Called when the activity is first created. */
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

		Toast.makeText(this, "Activity onCreate", Toast.LENGTH_LONG).show();

		setContentView(R.layout.navigate_store);
		
		myGrid = new Grid();
		myGrid.build();
		myAccel = new Accelerometer();
		myAccel.readCSV();

		mySurfaceView = (MySurfaceView) findViewById(R.id.myCustomSurface);

		Button startStopButton = (Button) findViewById(R.id.startStopButton);
		final Button gotItemButton = (Button) findViewById(R.id.gotItemButton);

//		final Spinner mySpinner = (Spinner) findViewById(R.id.spinner);
//		adapter = new ArrayAdapter<String>(this,
//				android.R.layout.simple_spinner_item, dotColor);
//		adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
//		mySpinner.setAdapter(adapter);

		startStopButton.setOnClickListener(new Button.OnClickListener() {

			@Override
			public void onClick(View arg0) {
				if (gotItemButton.getVisibility() == View.VISIBLE) {
					gotItemButton.setVisibility(View.GONE);
				} else {
					gotItemButton.setVisibility(View.VISIBLE);
				}
			}

		});

		gotItemButton.setOnClickListener(new Button.OnClickListener() {

			@Override
			public void onClick(View arg0) {
				System.out.println("Got item");
			}
		});

		//mySpinner.setOnItemSelectedListener(mySpinnerOnItemSelectedListener);
	}

//	private Spinner.OnItemSelectedListener mySpinnerOnItemSelectedListener = new Spinner.OnItemSelectedListener() {
//
//		@Override
//		public void onItemSelected(AdapterView<?> arg0, View arg1, int arg2,
//				long arg3) {
//			String selectedColor = arg0.getItemAtPosition(arg2).toString();
//			if (selectedColor == "White") {
//				mySurfaceView.setDotColor(Color.WHITE);
//			} else if (selectedColor == "Red") {
//				mySurfaceView.setDotColor(Color.RED);
//			} else if (selectedColor == "Green") {
//				mySurfaceView.setDotColor(Color.GREEN);
//
//			} else {
//				mySurfaceView.setDotColor(Color.BLUE);
//			}
//		}
//
//		@Override
//		public void onNothingSelected(AdapterView<?> arg0) {
//			
//
//		}
//
//	};

	public static class MySurfaceView extends SurfaceView implements
			SurfaceHolder.Callback {

		private MySurfaceThread thread;
		private Paint paint = new Paint(Paint.ANTI_ALIAS_FLAG);
		int cx, cy, offx, offy;
		RectF storeLayout;
		ArrayList<Float> aisleLayout = new ArrayList<Float>();

		boolean storeComputed = false;
		

		public MySurfaceView(Context context) {
			super(context);
			init();
		}
		
		void computeStore(Canvas canvas) {
			int canvasWidth = canvas.getWidth();
			int gridWidth = myGrid.getDimensions()[0];
			int gridHeight = myGrid.getDimensions()[1];
			float gridRatio = (float)gridWidth / (float)gridHeight;		
			
			
			storeLayout = new RectF(0,0,canvasWidth,canvasWidth * gridRatio);
			float storeFloorFactorW = storeLayout.width() / gridWidth;
            float storeFloorFactorH = storeLayout.height() / gridHeight;

			Iterator<int[]> aisleItr = myGrid.getAisles().iterator();
			
			while(aisleItr.hasNext()) {
				int[] a = aisleItr.next();
				
				aisleLayout.add( ((float) a[0]) * storeFloorFactorW);
				aisleLayout.add( ((float) a[1]) * storeFloorFactorH);
				aisleLayout.add( ((float) a[2]) * storeFloorFactorW);
				aisleLayout.add( ((float) a[3]) * storeFloorFactorH);
			}
			storeComputed = true;
			
		}
		
		public static float[] convertFloats(List<Float> floats)
		{
		    float[] ret = new float[floats.size()];
		    Iterator<Float> iterator = floats.iterator();
		    for (int i = 0; i < ret.length; i++)
		    {
		        ret[i] = iterator.next().floatValue();
		    }
		    return ret;
		}
		
		void drawStore(Canvas canvas) {
			if(storeComputed) {
			Paint p = new Paint(Paint.ANTI_ALIAS_FLAG);
			
			//Draw Store
			p.setStyle(Paint.Style.FILL);
			p.setColor(Color.LTGRAY);
			canvas.drawRect(storeLayout, p);
			
			//Draw Aisles
			p.setStyle(Paint.Style.STROKE);
			p.setStrokeWidth(10);
			p.setColor(Color.DKGRAY);
			float[] lines = convertFloats(aisleLayout);
			canvas.drawLines(lines, p);
			}
		}
		
		

		public MySurfaceView(Context context, AttributeSet attrs) {
			super(context, attrs);
			init();
		}

		public MySurfaceView(Context context, AttributeSet attrs, int defStyle) {
			super(context, attrs, defStyle);
			init();
		}

		private void init() {
			getHolder().addCallback(this);

			// thread = new MySurfaceThread(getHolder(), this);

			setFocusable(true); // make sure we get key events

			paint.setStyle(Paint.Style.STROKE);
			paint.setStrokeWidth(3);
			paint.setColor(Color.WHITE);

			cx = 0;
			cy = 0;
			offx = 20;
			offy = 20;

			Toast.makeText(getContext(), "SurfaceView Constructor",
					Toast.LENGTH_LONG).show();

		}

		@Override
		public void surfaceChanged(SurfaceHolder arg0, int arg1, int arg2,
				int arg3) {
			Toast.makeText(getContext(), "surfaceChanged", Toast.LENGTH_LONG)
					.show();

		}

		@Override
		public void surfaceCreated(SurfaceHolder holder) {
			Toast.makeText(getContext(), "surfaceCreated", Toast.LENGTH_LONG)
					.show();

			thread = new MySurfaceThread(getHolder(), this);
			thread.setRunning(true);

			thread.start();
		}

		@Override
		public void surfaceDestroyed(SurfaceHolder holder) {
			Toast.makeText(getContext(), "surfaceDestroyed", Toast.LENGTH_LONG)
					.show();

			boolean retry = true;
			thread.setRunning(false);
			while (retry) {
				try {
					thread.join();
					retry = false;
				} catch (InterruptedException e) {
				}
			}
		}

		@Override
		protected void onDraw(Canvas canvas) {
			if(myAccel.size() == 0) {
				System.out.println("Done!");
				thread.setRunning(false);
			}
			int[] accl = myAccel.getFirst();
			long time = accl[0] * 1000;
			int distance = accl[1];
			int direction = accl[2];
			
			running_time += 100;
			if(running_time == (long)time) {
				myAccel.popFirst();
				myGrid.setLocation(distance, direction);
			}
			
			
			if(storeComputed) {
				float storeFloorFactorW = storeLayout.width() / myGrid.getDimensions()[0];
                float storeFloorFactorH = storeLayout.height() / myGrid.getDimensions()[1];
				drawStore(canvas);
				
				//Draw User location
				int locX = myGrid.getLocX();
				int locY = myGrid.getLocY();
				paint.setColor(Color.YELLOW);
				canvas.drawCircle(locX*storeFloorFactorW, locY*storeFloorFactorH, 5, paint);
			}
			else
				computeStore(canvas);
			
			
			
		}

		public void setDotColor(int color) {
			paint.setColor(color);
		}
	}

	public static class MySurfaceThread extends Thread {
		private SurfaceHolder myThreadSurfaceHolder;
		private MySurfaceView myThreadSurfaceView;
		private boolean myThreadRun = false;

		public MySurfaceThread(SurfaceHolder surfaceHolder,
				MySurfaceView surfaceView) {
			myThreadSurfaceHolder = surfaceHolder;
			myThreadSurfaceView = surfaceView;
		}

		public void setRunning(boolean b) {
			myThreadRun = b;
		}

		@Override
		public void run() {
			while (myThreadRun) {
				Canvas c = null;

				try {
					c = myThreadSurfaceHolder.lockCanvas(null);
					synchronized (myThreadSurfaceHolder) {
						myThreadSurfaceView.onDraw(c);
					}
					sleep(100);
				} catch (InterruptedException e) {
					e.printStackTrace();
				} finally {
					// do this in a finally so that if an exception is thrown
					// during the above, we don't leave the Surface in an
					// inconsistent state
					if (c != null) {
						myThreadSurfaceHolder.unlockCanvasAndPost(c);
					}
				}
			}
		}
	}

}